<template>
    <div class="mainBody">
        <div>
            <Nav />
        </div>
        <div class="mainContainer">
            <div class="category_select">
                <el-select v-model="value" placeholder="Select" size="large" style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <div style="padding-top: 10px;">
                    当前标签: {{ selectedTag }}
                </div>
            </div>
            <el-divider />

            <div class="category_box">
                <div class="category_book">
                    <div class="category_book_item" v-for="(book, index) in currentPageBooks" :key="index">
                        <div class="category_img">
                            <div :style="{ backgroundImage: `url(${book.cover_url})` }" class="category_bookCover"
                                @click="navigateToBook(book.id)">
                            </div>
                        </div>
                        <div class="category_bookInfo">
                            <p class="bookName1 turnRed" @click="navigateToBook(book.id)">{{ book.name }}</p>
                            <p class="bookAuthor_hot_characterCount1">
                                <span @click="navigateToAuthor(book.author.author_id)" class="turnRed">
                                    {{ book.author.author_name }}
                                </span>
                                <span> | </span>
                                <span>
                                    {{ book.hot_number }}热度
                                </span>
                                <span> | </span>
                                <span>
                                    {{ book.word_count }}字
                                </span>
                            </p>

                            <p class="bookDescription1 turnRed" @click="navigateToBook(book.id)">{{
                                cut(book.description, 50) }}</p>

                            <p class="bookType1">
                                关键词:
                                <span v-for="(tag, index) in book.tag.slice(0, 5)" :key="index" class="turnRed" @click="navigateToCategory(tag)">
                                    {{ tag }}
                                    <span v-if="index < book.tag.slice(0, 5).length - 1"> , </span>
                                </span>
                            </p>
                            
                        </div>

                        <Button2 class="search_read_button" @click="navigateToBook(book.id)">
                            <div>立即阅读</div>
                        </Button2>
                    </div>
                </div>

                <div class="category_all">
                    <div class="category_concrete">
                        <div class="category_concrete_font">
                            所有标签
                        </div>
                        <Button1 v-for="(category, index) in categories" :key="index" class="category_button"
                            @click="navigateToCategory(category), handleTagChange(category)">
                            <div>
                                {{ category }}
                            </div>
                        </Button1>
                    </div>
                    <recommend />
                </div>
            </div>
            <div class="category_pages">
                <el-pagination :current-page="currentPage" :page-size="pageSize" layout="prev, pager, next"
                    :total="totalBooks" @current-change="handlePageChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { fetchBooks, books, totalBooks } from '@/apis/getBooks_by_tags.js';
import { getBookTags } from '@/apis/getTags.js';
import { useNavigation } from '@/utils/navigate.js';
import { cut } from '@/utils/cutText.js';
import '@/display/bookInfo.css';
import '@/display/mainBody.css';
import '@/display/fontTurnRed.css';
import Button1 from '@/components/button1.vue';
import Button2 from '@/components/button2.vue';
import recommend from '@/components/trending.vue';

const { proxy } = getCurrentInstance();
const { navigateToCategory, navigateToBook, navigateToAuthor } = useNavigation(); //导入导航函数
const router = useRouter(); //路由对象
const route = useRoute(); //当前路由对象

const currentPage = ref(1);  //默认第一页
const pageSize = ref(16);  //一页16本书

const categories = ref([]); //所有类别信息

const selectedTag = ref(null); 

const value = ref('1'); //选择器默认第一个

const options = [
    { value: '1', label: '最新发布', },
    { value: '2', label: '最多阅读', },
    { value: '3', label: '最近更新', },
    { value: '4', label: '最多收藏', },
]

// 排序函数
const sortBooks = () => {
    if (value.value == '1')
        books.value.sort((a, b) => new Date(b.time_published) - new Date(a.time_published));
    else if (value.value == '2')
        books.value.sort((a, b) => b.reader_number - a.reader_number);
    else if (value.value == '3')
        books.value.sort((a, b) => new Date(b.time_updated) - new Date(a.time_updated));
    else if (value.value == '4')
        books.value.sort((a, b) => b.like_number - a.like_number);
}

watch(value, () => {
    sortBooks();
})


watch(route, (newRoute) => {
    const category = newRoute.params.select;
    selectedTag.value = category;
    fetchBooks(category, proxy);
    sortBooks();
}, { immediate: true });

const currentPageBooks = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    return books.value.slice(startIndex, endIndex)
})

onMounted(async () => {
    const uniqueCategories = await getBookTags(proxy);
    if (uniqueCategories) {
        categories.value = ['全部类别', ...new Set(uniqueCategories)];
    }
});

// 处理翻页  
function handlePageChange(newPage) {
    currentPage.value = newPage
    //翻页后平滑回到顶部
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

function handleTagChange(category) {
    let tag = null;
    selectedTag.value = category;
    if (category === '全部类别')
        tag = 'all';
    else
        tag = encodeURIComponent(category);

    console.log(tag);
    fetchBooks(tag, proxy);
    sortBooks();
}

</script>

<style scoped>
.category_select {
    padding: 25px 0 0 100px;
}

.category_box {
    display: flex;
    padding: 0 30px 0 30px;
}

.category_book {
    flex: 7;
    display: flex;
    flex-direction: column;
}

.category_book_item {
    padding: 30px;
    display: flex;
    align-items: center;
}

.category_img {
    display: flex;
    align-items: center;
}

.category_bookCover {
    height: 160px;
    width: 120px;
    background-size: 100% 100%;
    border-radius: 7px;
    transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
    cursor: pointer;
}

.category_bookCover:hover {
    transform: scale(1.1);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}

.category_bookInfo {
    height: 160px;
    width: 400px;
    margin: 0 0 0 50px;
    text-align: left;
}

.category_all {
    flex: 3;
    height: 1200px;
    display: flex;
    flex-direction: column;
    border-radius: 10px;
}

.category_concrete {
    margin: 0 0 50px 0;
    height: 300px;
    border: 1px solid rgb(207, 204, 204);
    overflow: auto;
}

.category_concrete_font {
    padding: 20px 0 0 20px;
    font-size: 20px;
}

.category_button {
    width: 50px;
    margin: 30px 30px 0 30px;
    display: inline-block;
}

.search_read_button {
    margin-left: 70px;
}

.category_pages {
    display: flex;
    justify-content: center;
    padding: 20px 0 20px 0;
}
</style>
